package com.lancoo.znbkxx.teacher.aibkGenerateTestPaper.aibkPreviewTemplet

import android.content.Context
import android.content.Intent
import android.os.Handler
import android.os.IBinder
import android.text.Html
import android.util.Log
import android.view.MotionEvent
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.gson.Gson
import com.lancoo.znbkxx.teacher.R
import com.lancoo.znbkxx.teacher.aibkGenerateTestPaper.aibkCustomTemplet.AibkCustomTempletAdapter
import com.lancoo.znbkxx.teacher.aibkGenerateTestPaper.aibkCustomTemplet.CustomQuesTypeInfor
import com.lancoo.znbkxx.teacher.aibkGenerateTestPaper.aibkCustomTemplet.CustomTemplet
import com.lancoo.znbkxx.teacher.aibkGenerateTestPaper.aibkCustomTemplet.jsonHelp
import com.lancoo.znbkxx.teacher.aibkGenerateTestPaper.aibkGenerateDialog.DialogTempletQuesTypeChoose
import com.lancoo.znbkxx.teacher.aibkGenerateTestPaper.aibkGenerateDialog.DialogTempletQuesTypeRevise
import com.lancoo.znbkxx.teacher.aibkGenerateTestPaper.aibkGeneratePaper.itemtouchhelper.MyItemTouchHelperCallback
import com.lancoo.znbkxx.teacher.aibkGenerateTestPaper.aibkGeneratePaper.itemtouchhelper.OnStartDragListener
import com.lancoo.znbkxx.teacher.aibkGenerateTestPaper.aibkGeneratePaper.itemtouchhelper.SwipeMenuLayout
import com.lancoo.znbkxx.teacher.aibkTestCoach.aibkTools.LancooMethod
import com.lancoo.znbkxx.teacher.aibkTestCoach.aibkTools.MyToast
import com.lancoo.znbkxx.teacher.aibkTestCoach.kBase.KBaseActivity
import com.lancoo.znbkxx.teacher.aibkTestCoach.networkRequest.bindLifeCycle
import com.lancoo.znbkxx.teacher.aibkTestCoach.networkRequest.entity.TemplateTypeListInfor
import com.lancoo.znbkxx.teacher.aibkTestCoach.networkRequest.entity.TempletSelectedTypeListInfor
import com.lancoo.znbkxx.teacher.aibkTestCoach.networkRequest.viewModel.MarkViewModel
import com.lancoo.znbkxx.teacher.help.KeyboardStateObserverHelp
import com.lancoo.znbkxx.teacher.utils.ButtonUtils
import kotlinx.android.synthetic.main.aibk_activity_template_custom.*
import kotlinx.android.synthetic.main.aibk_activity_template_preview.*
import kotlinx.android.synthetic.main.aibk_activity_template_preview.BtnListTemplateAdd
import kotlinx.android.synthetic.main.aibk_activity_template_preview.IvBack
import kotlinx.android.synthetic.main.aibk_activity_template_preview.TvSaveCustomTemplet
import kotlinx.android.synthetic.main.aibk_adapter_item_empty.*
import kotlinx.android.synthetic.main.aibk_include_layout_template_name.*
import kotlinx.android.synthetic.main.aibk_include_layout_template_overview.*
import kotlinx.android.synthetic.main.aibk_include_loading_refresh.*
import org.koin.androidx.viewmodel.ext.android.viewModel
import java.util.ArrayList

/*
* 模板预览
* */
class AibkTempletPreviewActivity : KBaseActivity(), View.OnClickListener, OnStartDragListener  {

    private var templetType = 0
    private var templetId = ""
    private var templetName = ""
    private var typeCount = 0
    private var itemCount = 0
    private var fullScore = 0.0
    private var answerLength = 0

    companion object {
        fun launch(activity: AppCompatActivity, templetType:Int, templetId: String, templetName: String, typeCount: Int, itemCount: Int, fullScore: Double, answerLength: Int) {
            val intent = Intent(activity, AibkTempletPreviewActivity::class.java)
            intent.putExtra("TempletType", templetType)
            intent.putExtra("TempletId", templetId)
            intent.putExtra("TempletName", templetName)
            intent.putExtra("TypeCount", typeCount)
            intent.putExtra("ItemCount", itemCount)
            intent.putExtra("FullScore", fullScore)
            intent.putExtra("AnswerLength", answerLength)
//            context.startActivity(intent)
            activity.startActivityForResult(intent,303)
        }
    }

    private val mViewModel: MarkViewModel by viewModel()
    private var templateTypeListInfor: TemplateTypeListInfor? = null
    private var mItemTouchHelper: ItemTouchHelper? = null
    private var customTemplet: CustomTemplet? = null
    private var mCustomTempletAdapter:AibkCustomTempletAdapter? = null
    private var templetSelectedTypeListInfor: TempletSelectedTypeListInfor? = null

    override fun setLayout(): Int {
        return R.layout.aibk_activity_template_preview
    }

    override fun initView() {
        IvBack.setOnClickListener(this)
        //另存为按钮
        TvSaveCustomTempletAnother.setOnClickListener(this)
        //保存按钮
        TvSaveCustomTemplet.setOnClickListener(this)
        //新增按钮
        BtnListTemplateAdd.setOnClickListener(this)

        KeyboardStateObserverHelp.getKeyboardStateObserver(this)
                .setKeyboardVisibilityListener(object : KeyboardStateObserverHelp.OnKeyboardVisibilityListener {
                    override fun onKeyboardShow() {

                    }

                    override fun onKeyboardHide() {
                        val suggestAnswerTimeX = EdtSuggestAnswerTime.text.toString()
                        val suggestAnswerTime = Math.abs(suggestAnswerTimeX.toInt())
                        EdtSuggestAnswerTime.setText(suggestAnswerTime.toString())
                    }
                })

        mViewModel.getSelectedTypeList(templetType)
                .doOnSubscribe {
                    RlGifLoading.visibility = View.VISIBLE
                }.bindLifeCycle(this)
                .subscribe({
                    if (it.code == 1) {

                        templetSelectedTypeListInfor = it.data

                        initCustomQuesType()

                    } else {
                        MyToast.showToast(it.message)
                        Handler().postDelayed({
                            finish()
                        }, 500)
                    }
                }, {
                    MyToast.showToast(it.message)
                    Handler().postDelayed({
                        finish()
                    }, 500)
                })
    }

    override fun initData() {
        templetType = intent.getIntExtra("TempletType", 0)
        templetId = intent.getStringExtra("TempletId")
        templetName = intent.getStringExtra("TempletName")
        typeCount = intent.getIntExtra("TypeCount",0)
        itemCount = intent.getIntExtra("ItemCount",0)
        fullScore = intent.getDoubleExtra("FullScore",0.0)
        answerLength = intent.getIntExtra("AnswerLength",0)

        //获取模板管理的选中模板的题型信息
        mViewModel.getTempletTypeList(templetId)
                .doOnSubscribe {
                    RlGifLoading.visibility = View.VISIBLE
                }.bindLifeCycle(this)
                .subscribe({
                    if (it.code == 1) {
                        RlGifLoading.visibility = View.GONE

                        templateTypeListInfor = it.data
                        showPreviewView()
                    } else {
                        MyToast.showToast(it.message)
                        Handler().postDelayed({
                            finish()
                        }, 500)
                    }
                }, {
                    MyToast.showToast(it.message)
                    Handler().postDelayed({
                        finish()
                    }, 500)
                })
    }

    private fun showPreviewView() {
        //显示模范名称
        EdtCustomTemplateName.setText(templetName)

        //显示模板概要
        showTempletTitleInfor(typeCount, itemCount, fullScore)

        //显示模板建议作答时长
        EdtSuggestAnswerTime.setText(answerLength.toString())

        //显示模板题型信息
        var manager = LinearLayoutManager(this)
        manager.orientation = LinearLayoutManager.VERTICAL
        RvTemplatePreview.layoutManager = manager

        /*************************************************************/
        val templateTypeListInforSize = templateTypeListInfor!!.size
        if(templateTypeListInforSize>0){
            LlEmptyListView.visibility = View.GONE
        }else{
            LlEmptyListView.visibility = View.VISIBLE
        }
        Log.e("ppsspp", "======templateTypeListInforSize=======" + templateTypeListInforSize)
        for(i in 0 until templateTypeListInforSize) {
            val aibk_typeNo = templateTypeListInfor!![i].TypeNo
            val aibk_typeName = templateTypeListInfor!![i].TypeName
            val aibk_genreId = templateTypeListInfor!![i].GenreID
            val aibk_genreName = templateTypeListInfor!![i].GenreName
            val currentBigQuesCount = templateTypeListInfor!![i].QuesList.size
            val currentSmallItemCount = templateTypeListInfor!![i].QuesList[0].ItemNum
            val currentEachScore = templateTypeListInfor!![i].QuesList[0].ScoreList
            val aibk_specialFeatureCodes = templateTypeListInfor!![i].SpecialFeatureCodes

            val strSingleCustomQuesInfor = Gson().toJson(jsonHelp.getLastCustomQues(
                    aibk_typeNo, aibk_typeName, aibk_genreId, aibk_genreName,
                    currentBigQuesCount, currentSmallItemCount, currentEachScore,
                    aibk_specialFeatureCodes
            ))
            Log.e("ppsspp", "======组装的内容=======" + strSingleCustomQuesInfor)
            val customQuesTypeInfor = Gson().fromJson(strSingleCustomQuesInfor, CustomQuesTypeInfor::class.java)

            var contentSize = 1
            if(customTemplet!=null) {
                contentSize = customTemplet!!.Content.size + 1
            }
            Log.e("ppsspp", "======contentSize=======" + contentSize)
            val strCustomtemplet = Gson().toJson(jsonHelp.getCustomTemplet(
                    customTemplet,
                    contentSize,
                    customQuesTypeInfor,
                    0,
                    templetType,
                    EdtSuggestAnswerTime.text.toString().toInt(),
                    EdtCustomTemplateName.text.toString(),
                    ""
            ))
            Log.e("==ppsspp==", "===hahah===自定义模板()=====$strCustomtemplet")
            customTemplet = Gson().fromJson(strCustomtemplet, CustomTemplet::class.java)
        }

        mCustomTempletAdapter = AibkCustomTempletAdapter(this, customTemplet, this)
        mCustomTempletAdapter!!.setOnDelListener(object : AibkCustomTempletAdapter.OnSwipeListener {
            override fun onTempletDelete(view: View?, pos: Int) {
                //删除模板
                val swipeMenuLayout: SwipeMenuLayout = view as SwipeMenuLayout
                swipeMenuLayout.quickClose()
                if(customTemplet!!.Content.size>0){
                    LlEmptyListView.visibility = View.GONE
                }else{
                    LlEmptyListView.visibility = View.VISIBLE
                }
            }

            override fun onTempletRevise(customTemplet: CustomTemplet, pos: Int) {
                //修改模板
                val dialogTemplateQuesTypeRevise = DialogTempletQuesTypeRevise(
                        this@AibkTempletPreviewActivity,
                        this@AibkTempletPreviewActivity,
                        templetSelectedTypeListInfor!!,
                        pos,
                        customTemplet)
                dialogTemplateQuesTypeRevise.setClickDialogListener(object : DialogTempletQuesTypeRevise.OnClickDialogListener {
                    override fun onClickRevise() {

                        //以上得到最新的组卷模板后刷新自定义试题列表
                        refreshQuesTypeListView()
                        //刷新模板头部总概详情
                        var totalQuesCount = 0
                        var totalItemCount = 0
                        var totalScore = 0.0

                        if(customTemplet!=null) {
                            val contentSize = customTemplet!!.Content.size
                            for (i in 0 until contentSize) {
                                val quesListSize = customTemplet!!.Content[i].QuesList.size
                                for (j in 0 until quesListSize) {
                                    val itemNum = customTemplet!!.Content[i].QuesList[j].ItemNum
                                    totalItemCount += itemNum
                                    val eachSocre = customTemplet!!.Content[i].QuesList[j].ScoreList[0]
                                    val totalScoreX = itemNum * eachSocre

                                    totalScore += totalScoreX
                                }
                                totalQuesCount += quesListSize
                            }
                        }
                        showTempletTitleInfor(totalQuesCount,totalItemCount,totalScore)
                    }

                    override fun onClickCloseRevise() {
                        initCustomQuesType()//刷新适用模板原始数据
                    }
                })
                dialogTemplateQuesTypeRevise.show()

            }
        })
        RvTemplatePreview.adapter = mCustomTempletAdapter
        mItemTouchHelper = ItemTouchHelper(MyItemTouchHelperCallback(mCustomTempletAdapter))
        mItemTouchHelper!!.attachToRecyclerView(RvTemplatePreview)
    }

    private fun showTempletTitleInfor(totalQuesCount:Int,totalItemCount:Int,totalScore:Double){
        TvTemplateInfor.text = Html.fromHtml(resources.getString(R.string.aibk_templet_infor,
                totalQuesCount, totalItemCount, LancooMethod.killlingDouble(totalScore)))
    }

    private fun initCustomQuesType() {
        val typeListSize = templetSelectedTypeListInfor!!.size
        for (i in 0 until typeListSize) {
            templetSelectedTypeListInfor!![i].IsChecked = false//初始化默认所有自定义模板试题均未被选中
//            templetSelectedTypeListInfor!![i].QuesCount = 1//初始化默认题型试题数为1
            templetSelectedTypeListInfor!![i].CountList[0].ItemScore = templetSelectedTypeListInfor!![i].CountList[0].EachScore//初始化默认题型试分值为0.5
            templetSelectedTypeListInfor!![i].ItemCountCheckedPosition = 0//初始化小题数量index为0：最小值

            val countListSize = templetSelectedTypeListInfor!![i].CountList.size
            for (j in 0 until countListSize) {
                templetSelectedTypeListInfor!![i].CountList[j].AttachedCheckedPosition = 0//初始化附加项index为0：无
            }
        }
    }

    private fun refreshQuesTypeListView() {
        if(customTemplet!!.Content.size>0){
            LlEmptyListView.visibility = View.GONE
        }else{
            LlEmptyListView.visibility = View.VISIBLE
        }
        mCustomTempletAdapter!!.refreshView(customTemplet!!)
    }

    override fun onStartDrag(viewHolder: RecyclerView.ViewHolder?) {
        mItemTouchHelper!!.startDrag(viewHolder!!)
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.IvBack -> {
                finish()
            }
            R.id.TvSaveCustomTempletAnother ->{
                //另存为
                val strEdtCustomTemplateName = EdtCustomTemplateName.text.toString()
                val intEdtSuggestAnswerTime = EdtSuggestAnswerTime.text.toString().toInt()

                if(customTemplet!=null) {
                    val contentSize = customTemplet!!.Content.size
                    if (contentSize > 0) {
                        if (strEdtCustomTemplateName.isEmpty() && Math.abs(intEdtSuggestAnswerTime) == 0) {
                            MyToast.showToast("请输入模板名称和建议作答时长")
                        } else if (strEdtCustomTemplateName.isEmpty() && Math.abs(intEdtSuggestAnswerTime) > 0) {
                            MyToast.showToast("请输入模板名称")
                        } else if (strEdtCustomTemplateName.isNotEmpty() && Math.abs(intEdtSuggestAnswerTime) == 0) {
                            MyToast.showToast("请输入建议作答时长")
                        } else if(strEdtCustomTemplateName.isNotEmpty() && Math.abs(intEdtSuggestAnswerTime)>0){
                            customTemplet!!.AnswerLength = intEdtSuggestAnswerTime
                            customTemplet!!.TempletName = strEdtCustomTemplateName
                            customTemplet!!.State = 1
                            mViewModel.saveCustomizeTemplet(Gson().toJson(customTemplet))
                                    .doOnSubscribe {
                                        startLoad()
                                    }.bindLifeCycle(this)
                                    .subscribe({
                                        if (it.code == 1) {
                                            stopLoad()
                                            finish()
                                        } else {
                                            stopLoad()
                                            MyToast.showToast(it.message)
                                        }
                                    }, {
                                        stopLoad()
                                        MyToast.showToast(it.message)
                                    })
                        }
                    } else if (contentSize == 0) {
                        if (strEdtCustomTemplateName.isEmpty() && Math.abs(intEdtSuggestAnswerTime) == 0) {
                            MyToast.showToast("请输入模板名称和建议作答时长,并设置模板题型")
                        } else if (strEdtCustomTemplateName.isEmpty() && Math.abs(intEdtSuggestAnswerTime) > 0) {
                            MyToast.showToast("请输入模板名称,并设置模板题型")
                        } else if (strEdtCustomTemplateName.isNotEmpty() && Math.abs(intEdtSuggestAnswerTime) == 0) {
                            MyToast.showToast("请输入建议作答时长,并设置模板题型")
                        }else if (strEdtCustomTemplateName.isNotEmpty() && Math.abs(intEdtSuggestAnswerTime) > 0) {
                            MyToast.showToast("请设置模板题型")
                        }
                    }
                }else{
                    if (strEdtCustomTemplateName.isEmpty() && Math.abs(intEdtSuggestAnswerTime) == 0) {
                        MyToast.showToast("请输入模板名称和建议作答时长,并设置模板题型")
                    } else if (strEdtCustomTemplateName.isEmpty() && Math.abs(intEdtSuggestAnswerTime) > 0) {
                        MyToast.showToast("请输入模板名称,并设置模板题型")
                    } else if (strEdtCustomTemplateName.isNotEmpty() && Math.abs(intEdtSuggestAnswerTime) == 0) {
                        MyToast.showToast("请输入建议作答时长,并设置模板题型")
                    }else if (strEdtCustomTemplateName.isNotEmpty() && Math.abs(intEdtSuggestAnswerTime) > 0) {
                        MyToast.showToast("请设置模板题型")
                    }
                }
            }
            R.id.TvSaveCustomTemplet ->{
                //保存：先删除再保存
                mViewModel.delCustomizeTemplet(templetId)
                        .doOnSubscribe {
                            startLoad()
                        }.bindLifeCycle(this)
                        .subscribe({
                            if (it.code == 1) {
                                val strEdtCustomTemplateName = EdtCustomTemplateName.text.toString()
                                val intEdtSuggestAnswerTime = EdtSuggestAnswerTime.text.toString().toInt()

                                if(customTemplet!=null) {
                                    val contentSize = customTemplet!!.Content.size
                                    if (contentSize > 0) {
                                        if (strEdtCustomTemplateName.isEmpty() && Math.abs(intEdtSuggestAnswerTime) == 0) {
                                            MyToast.showToast("请输入模板名称和建议作答时长")
                                        } else if (strEdtCustomTemplateName.isEmpty() && Math.abs(intEdtSuggestAnswerTime) > 0) {
                                            MyToast.showToast("请输入模板名称")
                                        } else if (strEdtCustomTemplateName.isNotEmpty() && Math.abs(intEdtSuggestAnswerTime) == 0) {
                                            MyToast.showToast("请输入建议作答时长")
                                        } else if(strEdtCustomTemplateName.isNotEmpty() && Math.abs(intEdtSuggestAnswerTime)>0){
                                            customTemplet!!.AnswerLength = intEdtSuggestAnswerTime
                                            customTemplet!!.TempletName = strEdtCustomTemplateName
                                            customTemplet!!.State = 1
                                            mViewModel.saveCustomizeTemplet(Gson().toJson(customTemplet))
                                                    .doOnSubscribe {
                                                        startLoad()
                                                    }.bindLifeCycle(this)
                                                    .subscribe({
                                                        if (it.code == 1) {
                                                            stopLoad()
                                                            finish()
                                                        } else {
                                                            stopLoad()
                                                            MyToast.showToast(it.message)
                                                        }
                                                    }, {
                                                        stopLoad()
                                                        MyToast.showToast(it.message)
                                                    })
                                        }
                                    } else if (contentSize == 0) {
                                        if (strEdtCustomTemplateName.isEmpty() && Math.abs(intEdtSuggestAnswerTime) == 0) {
                                            MyToast.showToast("请输入模板名称和建议作答时长,并设置模板题型")
                                        } else if (strEdtCustomTemplateName.isEmpty() && Math.abs(intEdtSuggestAnswerTime) > 0) {
                                            MyToast.showToast("请输入模板名称,并设置模板题型")
                                        } else if (strEdtCustomTemplateName.isNotEmpty() && Math.abs(intEdtSuggestAnswerTime) == 0) {
                                            MyToast.showToast("请输入建议作答时长,并设置模板题型")
                                        }else if (strEdtCustomTemplateName.isNotEmpty() && Math.abs(intEdtSuggestAnswerTime) > 0) {
                                            MyToast.showToast("请设置模板题型")
                                        }
                                    }
                                }else{
                                    if (strEdtCustomTemplateName.isEmpty() && Math.abs(intEdtSuggestAnswerTime) == 0) {
                                        MyToast.showToast("请输入模板名称和建议作答时长,并设置模板题型")
                                    } else if (strEdtCustomTemplateName.isEmpty() && Math.abs(intEdtSuggestAnswerTime) > 0) {
                                        MyToast.showToast("请输入模板名称,并设置模板题型")
                                    } else if (strEdtCustomTemplateName.isNotEmpty() && Math.abs(intEdtSuggestAnswerTime) == 0) {
                                        MyToast.showToast("请输入建议作答时长,并设置模板题型")
                                    }else if (strEdtCustomTemplateName.isNotEmpty() && Math.abs(intEdtSuggestAnswerTime) > 0) {
                                        MyToast.showToast("请设置模板题型")
                                    }
                                }
                            } else {
                                MyToast.showToast(it.message)
                            }
                        }, {
                            MyToast.showToast(it.message)
                        })


            }
            R.id.BtnListTemplateAdd -> {
                if (!ButtonUtils.isFastDoubleClick(R.id.BtnListTemplateAdd)) {
                    val dialogTemplateQuesTypeChoose = DialogTempletQuesTypeChoose(
                            this@AibkTempletPreviewActivity,
                            this@AibkTempletPreviewActivity,
                            templetSelectedTypeListInfor!!)
                    dialogTemplateQuesTypeChoose.setClickDialogListener(object : DialogTempletQuesTypeChoose.OnClickDialogListener {
                        override fun onClickAdd(customQuesTypeInfor: CustomQuesTypeInfor) {
//                            MyToast.showToast("新增加了一个题型")
                            initCustomQuesType()//刷新适用模板原始数据

                            var contentSize = 1
                            if (customTemplet != null) {
                                contentSize = 1 + customTemplet!!.Content.size
                            }
                            val strCustomtemplet = Gson().toJson(jsonHelp.getCustomTemplet(
                                    customTemplet,
                                    contentSize,
                                    customQuesTypeInfor,
                                    0,
                                    templetType,
                                    EdtSuggestAnswerTime.text.toString().toInt(),
                                    EdtCustomTemplateName.text.toString(),
                                    ""
                            ))
                            Log.e("==kankan==", "===hahah===自定义模板()=====$strCustomtemplet")
                            customTemplet = Gson().fromJson(strCustomtemplet, CustomTemplet::class.java)

                            //以上得到最新的组卷模板后刷新自定义试题列表
                            refreshQuesTypeListView()
                            //刷新模板头部总概详情
                            var totalQuesCount = 0
                            var totalItemCount = 0
                            var totalScore = 0.0

                            if(customTemplet!=null) {
                                val contentSize = customTemplet!!.Content.size
                                for (i in 0 until contentSize) {
                                    val quesListSize = customTemplet!!.Content[i].QuesList.size
                                    for (j in 0 until quesListSize) {
                                        val itemNum = customTemplet!!.Content[i].QuesList[j].ItemNum
                                        totalItemCount += itemNum
                                        val eachSocre = customTemplet!!.Content[i].QuesList[j].ScoreList[0]
                                        val totalScoreX = itemNum * eachSocre

                                        totalScore += totalScoreX
                                    }
                                    totalQuesCount += quesListSize
                                }
                            }
                            showTempletTitleInfor(totalQuesCount,totalItemCount,totalScore)
                        }

                        override fun onClickCloseChoose() {
                            initCustomQuesType()//刷新适用模板原始数据
                        }
                    })
                    dialogTemplateQuesTypeChoose.show()
                }
            }
        }
    }

}